package dal;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;
import bean.Task;

public class TaskDAL
{
  public Task get(int taskId)
  {
    Task task = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      task = (Task) session.load(Task.class, taskId);
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return task;
  }

  public Task save(Task task)
  {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      session.saveOrUpdate(task);
      transaction.commit();
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return task;
  }

  public void delete(Task task)
  {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      session.delete(task);
      transaction.commit();
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public int count()
  {
    int count = 0;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      count = ((Long) session.createQuery("SELECT COUNT(*) FROM Task")
          .uniqueResult()).intValue();
      transaction.commit();
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return count;
  }
}
